<template>
	<!-- 编辑走访记录
	 2025 废弃。改用企业经营情况登记表(/business/...) -->
	<view>
		<u-form class="form" :model="form" ref="uForm" label-width="180">
			<u-form-item label="走访时间" prop="visitTime">
				<u-input v-model="form.visitTime" @click="showVisitTime=true" />
				<!-- <view class="" @click="showVisitTime = true" style="width:100%;height:40px;background-color: antiquewhite;">{{form.visitTime}}</view> -->
				<u-calendar v-model="showVisitTime" mode="date" @change="changeVisitTime"></u-calendar>
			</u-form-item>
			<u-form-item label="走访人员" prop="visitBy" required>
				<u-input v-model="form.visitBy" />
			</u-form-item>
			<u-form-item label="企业名称" prop="companyName" required>
				<u-input v-model="form.companyName" />
			</u-form-item>
			<u-form-item label="经营地址" prop="companyAddress">
				<u-input v-model="form.companyAddress" />
			</u-form-item>
			<u-form-item label="联系人" prop="contactName">
				<u-input v-model="form.contactName" />
			</u-form-item>
			<u-form-item label="联系电话" prop="contactTel">
				<u-input v-model="form.contactTel" />
			</u-form-item>
			<u-form-item label="许可证号" prop="xukezhenghao">
				<u-input v-model="form.xukezhenghao" />
			</u-form-item>
			<u-form-item label="主营菜系" prop="cuisine">
				<u-input v-model="form.cuisine" />
			</u-form-item>
			<u-form-item label="经营面积" prop="operatingArea">
				<u-input v-model="form.operatingArea" />
			</u-form-item>
			<u-form-item label="人员数量" prop="personQuantity">
				<u-input v-model="form.personQuantity" />
			</u-form-item>
			<u-form-item label="食品安全总监" prop="fsd">
				<u-radio-group v-model="form.fsd">
					<u-radio v-for="(item, index) in fsdOptions" :key="index" :name="item.dictValue"
						:disabled="item.disabled">
						{{item.dictLabel}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="总监姓名" prop="fsdName" v-show="form.fsd == 1">
				<u-input v-model="form.fsdName" />
			</u-form-item>
			<u-form-item label="总监联系电话" prop="fsdTel" v-show="form.fsd == 1">
				<u-input v-model="form.fsdTel" />
			</u-form-item>
			<u-form-item label="体检情况" prop="tijianType">
				<u-radio-group v-model="form.tijianType">
					<u-radio v-for="(item, index) in tijianTypeOptions" :key="index" :name="item.dictValue"
						:disabled="item.disabled">
						{{item.dictLabel}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="体检医院" prop="tijianName" v-show="form.tijianType == 0">
				<u-input v-model="form.tijianName" />
			</u-form-item>
			<u-form-item label="体检价格" prop="tijianPrice" v-show="form.tijianType == 0">
				<u-input v-model="form.tijianPrice" />
			</u-form-item>
			<u-form-item label="体检到期时间" prop="tijianExpTime" v-show="form.tijianType == 0">
				<u-input v-model="form.tijianExpTime" @click="showTijianExpTime=true" />
				<u-calendar v-model="showTijianExpTime" mode="date" :max-date="maxDate" @change="changeTijianExpTime"></u-calendar>
			</u-form-item>
			<u-form-item label="消杀情况" prop="xiaoshaType">
				<u-radio-group v-model="form.xiaoshaType">
					<u-radio v-for="(item, index) in xiaoshaTypeOptions" :key="index" :name="item.dictValue"
						:disabled="item.disabled">
						{{item.dictLabel}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="消杀公司名称" prop="xiaoshaName" v-show="form.xiaoshaType == 1">
				<u-input v-model="form.xiaoshaName" />
			</u-form-item>
			<u-form-item label="检验检测" prop="jianceType">
				<u-radio-group v-model="form.jianceType">
					<u-radio v-for="(item, index) in jianceTypeOptions" :key="index" :name="item.dictValue"
						:disabled="item.disabled">
						{{item.dictLabel}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="检测公司名称" prop="jianceName" v-show="form.jianceType == 1">
				<u-input v-model="form.jianceName" />
			</u-form-item>
			<u-form-item label="特色礼盒" prop="gift">
				<u-radio-group v-model="form.gift">
					<u-radio v-for="(item, index) in giftOptions" :key="index" :name="item.dictValue"
						:disabled="item.disabled">
						{{item.dictLabel}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="礼盒食品品类" prop="giftName" v-show="form.gift == 1">
				<u-input v-model="form.giftName" />
			</u-form-item>
			<u-form-item label="预制菜" prop="preDishes">
				<u-radio-group v-model="form.preDishes">
					<u-radio v-for="(item, index) in preDishesOptions" :key="index" :name="item.dictValue"
						:disabled="item.disabled">
						{{item.dictLabel}}
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="预制菜品名称" prop="preDishesName" v-show="form.preDishes == 1">
				<u-input v-model="form.preDishesName" />
			</u-form-item>
			<u-form-item label="走访情况记录" prop="content">
				<u-input type="textarea" v-model="form.content" />
			</u-form-item>
			<u-form-item label="预估星级" prop="ranking">
				<u-input v-model="form.ranking" />
			</u-form-item>
			<u-form-item label="上传附件" prop="images">
				<u-upload ref="upload1"
					:action="uploadAction" 
					:file-list="fileList"
					:header="uploadHeader"
					:max-size="2 * 1024 * 1024" 
					max-count="9"
					@on-choose-complete="chooseComplete"
					@on-success="uploadSuccess"
					@on-error="uploadError"
					@on-uploaded="uploaded"
				></u-upload>
			</u-form-item>
		</u-form>

		<u-button type="primary" @click="submit" :disabled="disabled" :loading="loading">提交</u-button>
	</view>
</template>

<script>
	export default {
		data() {
			let form = {
				visitId: vk.getVuex('$user.userInfo.userId'),
				visitBy: vk.getVuex('$user.userInfo.nickName'),
				fsd: '1',
				tijianType: '0',
				xiaoshaType: '1',
				jianceType: '1',
				gift: '0',
				preDishes: '0',
			}
			return {
				disabled: false, // 提交中
				loading: false, // 提交中
				
				id: '',
				
				showVisitTime: false,
				showTijianExpTime: false,
				maxDate: '2050-12-31', // 日历的最大可选日期

				fsdOptions: [],
				tijianTypeOptions: [],
				xiaoshaTypeOptions: [],
				jianceTypeOptions: [],
				giftOptions: [],
				preDishesOptions: [],

				uploadAction: this.$api.uploadAction,
				fileList: [],
				uploadHeader: {},

				form,
				rules: {
					visitBy: [{
						required: true,
						message: '请输入走访人员',
						trigger: ['blur', 'change']
					}],
					companyName: [{
						required: true,
						message: '请输入企业名称',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		onLoad(options) {
			this.initPage(options)
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			changeVisitTime(e){
				this.form.visitTime = e.result;
			},
			changeTijianExpTime(e){
				this.form.tijianExpTime = e.result;
			},
			initPage(options = {}) {
				// console.log('this.$util.getToken()', this.$util.getToken());
				
				if(!this.$util.getToken()){
					this.$util.toLogin(()=>this.initPage())
				}
				
				let tokenStr = this.$util.getToken() ? 'Bearer ' + this.$util.getToken() : '';
				this.uploadHeader = {
					'Authorization': tokenStr
				}
				
				const eventChannel = this.getOpenerEventChannel();
				// 监听data事件，获取上一页面通过eventChannel.emit传送到当前页面的数据
				if (eventChannel.on) {
					eventChannel.on('data', (data) => {
						console.log('initPage', data)
						this.getData(data);
					});
				}

				this.getDicts("score_have_not", 'fsdOptions');
				this.getDicts("score_tijian_type", 'tijianTypeOptions');
				this.getDicts("score_xiaosha_type", 'xiaoshaTypeOptions');
				this.getDicts("score_jiance_type", 'jianceTypeOptions');
				this.getDicts("score_have_not", 'giftOptions');
				this.getDicts("score_have_not", 'preDishesOptions');
			},
			// 根据字典类型查询字典数据信息
			getDicts(dictType, optName) {
				this.$util.request(this.$api.GetDicts + dictType)
					.then(res => {
						this[optName] = res.data
					})
					.catch(err => {console.log('查询字典数据信息失败！', err);})
				// this[optName] = this.$dic.getDicts(dictType)
			},
			getData(options) {
				this.$util.request(this.$api.VisitInfo + 'info', {
						evaluateId: options.evaluateId
					})
					.then(res => {
						// console.log('走访记录详情 res', res);
						if(res.data){
							this.form = res.data
							this.fileList = this.form.images.split(',').map(item => {return {url: this.$resource.imageDomain + item}})
						}else{
							this.form = {
								id: null,
								visitTime: vk.pubfn.timeFormat(new Date(),"yyyy-MM-dd"),
								visitId: vk.getVuex('$user.userInfo.userId'),
								visitBy: vk.getVuex('$user.userInfo.nickName'),
								...options,
								tijianType: '0',
								xiaoshaType: '1',
								jianceType: '1',
								gift: '0',
								preDishes: '0',
							}
							this.fileList = [];
						}
						
					})
					.catch(err => {console.log('数据加载失败！', err);})
			},
			submit() {
				this.disabled = true;
				this.loading = true;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.submitForm();
					} else {
						this.disabled = false;
						this.loading = false;
					}
				});
			},
			submitForm(){
				let files = [];
				// 通过filter，筛选出上传进度为100的文件(因为某些上传失败的文件，进度值不为100，这个是可选的操作)
				files = this.$refs.upload1.lists.filter(val => {
					return val.progress == 100;
				})
				if(files && files.length > 0){
					this.form.images = '';
					let arr = files.map(item => {
						let url = item.response ? item.response.fileName : item.url;
						let i = url.indexOf(this.$resource.domain);
						if(i > -1) url = url.substring(this.$resource.domain.length-1, url.length)
						this.form.images += url + ',';
						return url;
					})
					// this.form.images = this.form.images.substring(0, this.form.images-1)
					this.form.images = arr.toString()
				}
				
				
				let method = this.id ? 'PUT' : 'POST';
				this.$util.request(this.$api.VisitRestful, this.form, method)
					.then(res => {
						if (res.code === 200) {
							vk.toast("保存成功", "success", 1000, true, () => {
								const eventChannel = this.getOpenerEventChannel();
								if (eventChannel.emit) eventChannel.emit('refresh');
								vk.navigateBack();
							});
						} else {
							console.log('保存失败', res)
							this.disabled = false;
							this.loading = false;
							vk.alert(res.msg, '保存失败');
						}
					}).catch((err) => {
						console.log('保存异常', err)
						this.disabled = false;
						this.loading = false;
						vk.alert(JSON.stringify(err), '保存异常');
					})
			},
			// 选择图片后触发
			chooseComplete(lists, name){
				if(!this.$util.getToken()){
					this.$util.toLogin(()=>this.initPage())
				}
			},
			// 图片上传成功时触发
			uploadSuccess(data, index, lists, name){
				console.log('图片上传成功', data, index, lists, name)
				// this.fileList = lists
			},
			// 图片上传失败时触发
			uploadError(data, index, lists, name){
				console.log('图片上传失败', data, index, lists, name)
			},
			// 所有图片上传完毕触发
			uploaded(lists, name){
				console.log('全部图片上传完成', lists, name)
				this.fileList = lists
			}
		}
	}
</script>

<style>
	.form {
		margin: auto;
		width: 90%;
	}
</style>